Skip to main content

React : Implementing Token-Based Authentication and Authorization with functional components

 

Token-based authentication is a popular approach for securing web applications, where users are issued tokens upon successful login, which are then used to access protected resources. In this blog post, we'll explore how to implement token-based authentication and authorization in a React application, including the use of authorization handlers for protected routes.

Step 1: Set Up the Backend: Begin by setting up a backend server (e.g., Node.js with Express or ASP.NET Core) to handle user authentication and token generation. Define endpoints for user login and token generation.

Step 2: Create React Application: Generate a new React application using Create React App or any other preferred method. This will serve as the frontend for our authentication system.

npx create-react-app my-auth-app
cd my-auth-app
Step 3: Implement Authentication Service: Create an authentication service in React to handle user login and token management. This service will make API calls to the backend for authentication.
// AuthService.js
const login = async (username, password) => {
  const response = await fetch('/api/login', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({ username, password })
  });
  const data = await response.json();
  return data.token; // Assuming the backend returns a token upon successful login
};

export default { login };
Step 4: Implement Login Component: Create a login component in React to allow users to log in with their credentials.
// LoginComponent.js
import React, { useState } from 'react';
import authService from './AuthService';

const LoginComponent = () => {
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');

  const handleSubmit = async (e) => {
    e.preventDefault();
    const token = await authService.login(username, password);
    console.log('Logged in with token:', token);
    // Redirect user to dashboard or protected route upon successful login
  };

  return (
    <form onSubmit={handleSubmit}>
      <input type="text" placeholder="Username" value={username} onChange={(e) => setUsername(e.target.value)} />
      <input type="password" placeholder="Password" value={password} onChange={(e) => setPassword(e.target.value)} />
      <button type="submit">Login</button>
    </form>
  );
}

export default LoginComponent;
Step 5: Protect Routes with Authorization Handler: Create an authorization handler in React to restrict access to protected routes based on user authentication status and token validity.
// AuthorizationHandler.js
import React, { useEffect, useState } from 'react';
import { Route, Redirect } from 'react-router-dom';
import authService from './AuthService';

const ProtectedRoute = ({ component: Component, ...rest }) => {
  const [authenticated, setAuthenticated] = useState(false);

  useEffect(() => {
    const checkAuthentication = async () => {
      const token = localStorage.getItem('token');
      if (token) {
        // Check token validity with backend
        // For simplicity, we'll assume token is valid
        setAuthenticated(true);
      }
    };
    checkAuthentication();
  }, []);

  return (
    <Route {...rest} render={(props) => (
      authenticated ? (
        <Component {...props} />
      ) : (
        <Redirect to="/login" />
      )
    )} />
  );
}

export default ProtectedRoute;
Step 6: Update App Component and Routing: Update the main App component to include routing and protect routes that require authentication.
// App.js
import React from 'react';
import { BrowserRouter as Router, Switch, Route } from 'react-router-dom';
import LoginComponent from './LoginComponent';
import DashboardComponent from './DashboardComponent'; // Example protected route
import ProtectedRoute from './AuthorizationHandler';

const App = () => {
  return (
    <Router>
      <Switch>
        <Route exact path="/login" component={LoginComponent} />
        <ProtectedRoute exact path="/dashboard" component={DashboardComponent} />
        {/* Add more protected routes as needed */}
      </Switch>
    </Router>
  );
}

export default App;
let's add two more pages as functional components, one of which will be accessible without authentication, and the other will require role-based authorization.

Step 7: Create Additional Pages (Functional Components):

Page 1: Home Page (Accessible without Authentication)
// HomePage.js
import React from 'react';

const HomePage = () => {
  return (
    <div>
      <h1>Welcome to Home Page</h1>
      <p>This is the home page of our application.</p>
    </div>
  );
}

export default HomePage;
Page 2: Admin Dashboard (Requires Role-Based Authorization)
// AdminDashboard.js
import React from 'react';

const AdminDashboard = () => {
  return (
    <div>
      <h1>Admin Dashboard</h1>
      <p>This is the admin dashboard page.</p>
    </div>
  );
}

export default AdminDashboard;

Step 8: Update App Component and Routing:

App.js

import React from 'react';
import { BrowserRouter as Router, Switch, Route } from 'react-router-dom';
import LoginComponent from './LoginComponent';
import HomePage from './HomePage'; // New page
import AdminDashboard from './AdminDashboard'; // New page
import ProtectedRoute from './AuthorizationHandler';

const App = () => {
  return (
    <Router>
      <Switch>
        <Route exact path="/login" component={LoginComponent} />
        <Route exact path="/" component={HomePage} /> {/* Home page accessible without authentication */}
        <ProtectedRoute exact path="/admin" component={AdminDashboard} roles={['admin']} /> {/* Admin dashboard requires role-based authorization */}
        {/* Add more protected routes as needed */}
      </Switch>
    </Router>
  );
}

export default App;
In this setup, the "Home" page is accessible without authentication, while the "Admin Dashboard" requires role-based authorization. The "ProtectedRoute" component checks if the user is authenticated and has the required role to access the protected route. This allows for a flexible and secure navigation experience in your React application.

Conclusion: By following the steps outlined in this blog post, you can implement token-based authentication and authorization in a React application. The authentication service handles user login and token management, while the authorization handler restricts access to protected routes based on user authentication status. With this setup, you can create secure and authenticated user experiences in your React applications.

Comments

Popular posts from this blog

Implementing and Integrating RabbitMQ in .NET Core Application: Shopping Cart and Order API

RabbitMQ is a robust message broker that enables communication between services in a decoupled, reliable manner. In this guide, we’ll implement RabbitMQ in a .NET Core application to connect two microservices: Shopping Cart API (Producer) and Order API (Consumer). 1. Prerequisites Install RabbitMQ locally or on a server. Default Management UI: http://localhost:15672 Default Credentials: guest/guest Install the RabbitMQ.Client package for .NET: dotnet add package RabbitMQ.Client 2. Architecture Overview Shopping Cart API (Producer): Sends a message when a user places an order. RabbitMQ : Acts as the broker to hold the message. Order API (Consumer): Receives the message and processes the order. 3. RabbitMQ Producer: Shopping Cart API Step 1: Install RabbitMQ.Client Ensure the RabbitMQ client library is installed: dotnet add package RabbitMQ.Client Step 2: Create the Producer Service Add a RabbitMQProducer class to send messages. RabbitMQProducer.cs : using RabbitMQ.Client; usin...

How Does My .NET Core Application Build Once and Run Everywhere?

One of the most powerful features of .NET Core is its cross-platform nature. Unlike the traditional .NET Framework, which was limited to Windows, .NET Core allows you to build your application once and run it on Windows , Linux , or macOS . This makes it an excellent choice for modern, scalable, and portable applications. In this blog, we’ll explore how .NET Core achieves this, the underlying architecture, and how you can leverage it to make your applications truly cross-platform. Key Features of .NET Core for Cross-Platform Development Platform Independence : .NET Core Runtime is available for multiple platforms (Windows, Linux, macOS). Applications can run seamlessly without platform-specific adjustments. Build Once, Run Anywhere : Compile your code once and deploy it on any OS with minimal effort. Self-Contained Deployment : .NET Core apps can include the runtime in the deployment package, making them independent of the host system's installed runtime. Standardized Libraries ...

.NET 10: Your Ultimate Guide to the Coolest New Features (with Real-World Goodies!)

 Hey .NET warriors! 🤓 Are you ready to explore the latest and greatest features that .NET 10 and C# 14 bring to the table? Whether you're a seasoned developer or just starting out, this guide will show you how .NET 10 makes your apps faster, safer, and more productive — with real-world examples to boot! So grab your coffee ☕️ and let’s dive into the awesome . 💪 1️⃣ JIT Compiler Superpowers — Lightning-Fast Apps .NET 10 is all about speed . The Just-In-Time (JIT) compiler has been turbocharged with: Stack Allocation for Small Arrays 🗂️ Think fewer heap allocations, less garbage collection, and blazing-fast performance . Better Code Layout 🔥 Hot code paths are now smarter, meaning faster method calls and fewer CPU cache misses. 💡 Why you care: Your APIs, desktop apps, and services now respond quicker — giving users a snappy experience . 2️⃣ Say Hello to C# 14 — More Power in Your Syntax .NET 10 ships with C# 14 , and it’s packed with developer goodies: Field-Bac...